package com.hama.iotrust.common.util;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

/**
 * CacheManager.getInstance() 默认以  /ehcache.xml 为配置
 */
public class EhcacheUtil {

    private static CacheManager manager = CacheManager.getInstance();

    /**
     * 将键值对存放到名称为cacheName的Cache下的某个Element
     */
    public static void put(String cacheName, String key, Object value) {
        Ehcache cache = manager.getEhcache(cacheName);
        if (cache == null) {
            manager.addCache(cacheName);
        }
        cache = manager.getEhcache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    /**
     * 返回名称为cacheName的，key为key的Element的值
     *
     * @param cacheName
     * @param key
     * @return
     */
    public static Object get(String cacheName, String key) {
        Ehcache cache = manager.getEhcache(cacheName);
        if (cache == null) return null;
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    /**
     * 得到名称为cacheName的Cache
     *
     * @param cacheName
     * @return
     */
    public static Ehcache get(String cacheName) {
        return manager.getEhcache(cacheName);
    }

    /**
     * 移除Cache的名称为cacheName下key为key的Element
     *
     * @param cacheName
     * @param key
     */
    public static void remove(String cacheName, String key) {
        Ehcache cache = manager.getEhcache(cacheName);
        if (cache != null) {
            cache.remove(key);
        }
    }
}
